package puyu.manage.service.SysUser.controller;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import puyu.manage.service.SysUser.service.SysUserServiceI;
import puyu.manage.service.common.config.BaseController;
import puyu.manage.service.common.page.TableDataInfo;
import puyu.manage.service.constant.AjaxResult;
import puyu.manage.service.security.LoginUser;
import puyu.manage.service.security.SecurityUtils;
import puyu.manage.service.security.service.TokenService;
import puyu.manage.service.utils.ServletUtils;
import puyu.manage.service.utils.UserConstants;
import puyu.manage.service.utils.except.CustomException;

import java.util.List;
import java.util.Map;

import static puyu.manage.service.constant.AjaxResult.error;
import static puyu.manage.service.constant.AjaxResult.success;

/**
 * 用户信息
 *
 * @author cxnet
 */
@Slf4j
@RestController
@Api(tags = "用户信息")
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired(required = false)
    private SysUserServiceI userService;
    @Autowired(required = false)
    private TokenService tokenService;
    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody Map<String,Object> user) {
        startPage();
        //根据条件分页查询用户列表
        List<Map<String,Object>> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表(不分页)")
    @GetMapping("/userNoPage")
    public AjaxResult userNoPage(Map<String,Object> user) {
        List<Map<String,Object>> list = userService.selectUserList(user);
        return AjaxResult.success(list);
    }

    private String convert(Object param) {
        return (null == param) ? "" : param.toString();
    }


    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody Map<String,Object> user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.get("userName")+""))) {
            return error("新增用户'" + user.get("userName") + "'失败，登录账号已存在");
        }
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PutMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(@RequestBody Map<String,Object> user) {
        //如果用户名字重复则添加数字
        Map<String,Object> userByNickName= userService.selectUserByNickName(user.get("nickName")+"");
        if (ObjectUtil.isNotEmpty(userByNickName)){
            return error("修改用户'" + userByNickName.get("nickName") + "'失败，用户名称已存在");
        }
        //判断是否存在相同用户账户
        Map<String,Object> userByName= userService.selectUserInfoByUserName(user.get("userName")+"");
        if (ObjectUtil.isNotEmpty(userByName)){
            return error("修改用户'" + userByName.get("userName") + "'失败，用戶账号已存在");
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 根据用户ID查询已赋权角色
     */
    @ApiOperation("根据用户ID查询已赋权角色")
    @GetMapping("/getByUserId")
    public AjaxResult getByUserId(@RequestParam(value = "userId") String userId) {
        List<Map<String,Object>> ids = userService.getByUserId(userId);
        return AjaxResult.success(ids);
    }

    /**
     * 用户与角色关联
     */
    @ApiOperation("用户与角色关联")
    @PutMapping("/userRole")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult userRole(@RequestBody Map<String,Object> userRole) {
        userService.userRole(userRole);
        return success("操作成功");
    }

    /**
     * 批量删除用户
     */
    @ApiOperation("批量删除用户")
    @DeleteMapping("/deleteById")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@RequestParam(value = "userIds") List<String> userIds) {
        userService.deleteUserByIds(userIds);
        return success("删除成功");
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @GetMapping("/resetPwd")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult resetPwd(@RequestParam(value = "userId") String userId) {
        userService.resetPwd(userId);
        return success("重置密码成功");
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PutMapping("/changeStatus")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeStatus(@RequestBody Map<String,Object> user) {
        userService.updateUserStatus(user);
        return success("状态修改成功");
    }

    /**
     * 修改密码
     */
    @ApiOperation("修改密码")
    @PutMapping("/updatePwd")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updatePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword")String newPassword) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            throw new CustomException("A0129");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            throw new CustomException("A0130");
        }
        return toAjax(userService.resetUserPwd(userName, newPassword));
    }

    /**
     * 弱密码检测-重置密码
     */
//    @ApiOperation("弱密码检测-重置密码")
//    @PutMapping("/changePwd")
//    public AjaxResult changePwd(@Validated @RequestBody SysUserInfo userInfo) {
//        return userService.changePwd(userInfo.getUserName(), userInfo.getNickName(), userInfo.getNewPassword(), userInfo.getOldPassword(), userInfo.getCode(), userInfo.getUuid());
//    }


    /**
     * 根据用户手机号获取用户数据
     **/
    @ApiOperation("根据用户手机号获取用户数据")
    @GetMapping("/getByUserPhone")
    public AjaxResult getByUserPhone(@RequestParam("phone") String phone) {
        Map<String,Object> map = userService.getByUserPhone(phone);
        return success(map);
    }


}
